<template>
  <div>
    <el-form :inline="true">
      <!--批次查询-->
      <el-form-item size="5">
        <el-input placeholder="批次查询" v-model="searchDto.batch" clearable></el-input>
      </el-form-item>
      <!--工厂查询-->
      <el-form-item>
        <el-select v-model="searchDto.factoryId" clearable placeholder="请选择工厂" v-if="roleType !== '4'">
          <el-option
            v-for="item1 in factoryOption"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <!--按省份查询-->
      <el-form-item>
        <el-select v-model="searchDto.provinceCode" clearable placeholder="请选择省份">
          <el-option
            v-for="item in allSelectProvince"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchReturn()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="exportLoading" @click="factoryOverviewExport()">数据导出</el-button>
      </el-form-item>
    </el-form>
    <el-tabs type="border-card" v-model="activeName1" @tab-click="unOperateClick(activeName1)">
      <el-tab-pane label="未结单" name="unOperate">
        <custom-table
          :data="overviewList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :pagination="pagination"
          :operationColumn="operationColumn">
        </custom-table>
      </el-tab-pane>

      <el-tab-pane label="已结单" name="alreadyOperate">
        <custom-table
          :data="overviewList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :pagination="pagination"
          :operationColumn="operationColumn">
        </custom-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="工厂收机详情" :visible.sync="detailDialogVisible" :close-on-click-modal="false">
      <!-- 工厂收机详情列表 -->
      <custom-table
        :data="detailList"
        :columns="detailColumns"
        :tableLoadingFlag="detailTableLoadingFlag"
        :pagination="pagination1">
      </custom-table>
      <div slot="footer">
        <el-button type="primary" @click="onBtnCancel()">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="返还详情" :visible.sync="backDialogVisible" :close-on-click-modal="false">
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick(activeName)">
        <el-tab-pane label="待返还" name="unReturn">
          <custom-table
            :data="unReturnList"
            :columns="unReturnColumn"
            :tableLoadingFlag="unReturnLoadingFlag"
            :pagination="unReturnPagination">
          </custom-table>
        </el-tab-pane>
        <el-tab-pane label="已返还" name="alreadyReturn">
          <custom-table
            :data="alreadyReturnList"
            :columns="alreadyReturnColumn"
            :tableLoadingFlag="alreadyReturnLoadingFlag"
            :pagination="alreadyReturnPagination">
          </custom-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer">
        <el-button type="primary" @click="onBtnClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {parseTime} from '@/utils'
  import CustomTable from '../../../components/table/CustomTable.vue'
  import RepairList from '../../../components/table/RepairList.vue'
  import {
    getRoleType,
    getOfficeType,
    getOutsourceType,
    getUserId
  } from '@/utils/token'
  import {apiGetFactoryList, apiGetCity} from '@/api/dictionary'
  import {
    apiGetFactoryBatchInfo,
    apiGetBatchDeviceInfo,
    apiGetBatchUnreturnDevice,
    apiGetBatchReturnedDevice,
    apiGetFactoryOverviewListExport
  } from '@/api/repairs/factory/index'
  import {downloadExcel} from "../../../utils";

  export default {
    components: {
      CustomTable,
      RepairList
    },
    name: 'return',
    created () {
      let listQuery = {
        status: 0,
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        userId: getUserId()
      }
      this.getReturnList(listQuery)
      this.getFactoryList()
      this.getSelectProvince()
    },
    data () {
      return {
        searchDto: {
          batch: undefined,
          factoryId: undefined,
          provinceCode: undefined
        },
        listQuery: {
          bach: undefined,
          factoryId: undefined,
          provinceCode: undefined
        },
        pickOption: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          }
        },
        userId: getUserId(),
        // 用户角色类型
        roleType: getRoleType(),
        // 办事处类型 0:省办事处，1:市办事处
        officeType: getOfficeType(),
        // 省外包商 1
        outSource: getOutsourceType(),
        activeName: 'unReturn',
        activeName1: 'unOperate',
        queryBatch: '',
        // 所有工厂一览选择
        factoryOption: [],
        // 所有省份一览选择
        allSelectProvince: [],
        tableLoadingFlag: false,
        detailTableLoadingFlag: false,
        alreadyReturnLoadingFlag: false,
        unReturnLoadingFlag: false,
        detailDialogVisible: false,
        backDialogVisible: false,
        columns: [
          {label: '月份', name: 'backTime', align: 'center', formatter: this.formatTime},
          {label: '返厂日期', name: 'backTime', width: '160', align: 'center', formatter: this.formatDate},
          {label: '返厂批次号', name: 'batch', width: '160', align: 'center'},
          {label: '省', name: 'provinceName', width: '80', align: 'center'},
          {label: '地市', name: 'cityName', align: 'center'},
          {label: '返还工厂', name: 'returnFactoryName', align: 'center'},
          {label: '型号', name: 'statistic', align: 'center'},
          {label: '返厂数量', name: 'returnNum', align: 'center'},
          {label: '已接收', name: 'receivedNum', align: 'center'},
          {label: '已拒收', name: 'refusedNum', align: 'center'},
          {label: '待维修', name: 'unRepairedNum', align: 'center'},
          {label: '已返还', name: 'returnedNum', align: 'center'},
          {label: '待返还', name: 'unReturnedNum', align: 'center'},
          {label: '网点待收机', name: 'unReceiptedNum', align: 'center'},
          {label: '欠单数量', name: 'oweDeviceNum', align: 'center', formatter: this.formatOweDeviceNum},
          {
            label: '接收日期',
            name: 'factoryReceiveTime',
            width: '160',
            align: 'center',
            formatter: this.formatReceiveTimestamp
          },
          {
            label: '返还日期',
            name: 'factoryReturnTime',
            width: '160',
            align: 'center',
            formatter: this.formatReturnTimestamp
          },
          {
            label: '在厂时间(天)',
            name: 'inFactoryTime',
            width: '120',
            align: 'center',
            formatter: this.formatInFactoryTime,
            renderHeader: this.renderHeader
          }
        ],
        // 操作栏
        operationColumn: {
          width: '100',
          operations: [
            {name: '接收详情', callback: this.onBtnReceive},
            {name: '返还详情', callback: this.onBtnBack}
          ]
        },
        detailColumns: [
          {label: '品牌', name: 'brandName', align: 'center'},
          {label: '型号', name: 'modelName', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', width: '80', align: 'center'},
          {label: '接收状态', name: 'status', align: 'center', formatter: this.formatStatus},
          {label: '操作人', name: 'receiverName', align: 'center'},
          {label: '接收时间', name: 'receiveTime', align: 'center'}
        ],
        alreadyReturnColumn: [
          {label: '返厂批次号', name: 'batch', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', align: 'center'},
          {label: '省份', name: 'province', width: '80', align: 'center'},
          {label: '型号', name: 'model', align: 'center'},
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '责任人', name: 'duty', align: 'center'},
          {label: '维修结果', name: 'repairResult', align: 'center'},
          {label: '返还时间', name: 'backTime', align: 'center'},
          {label: '物流公司', name: 'logisticsCompany', align: 'center'},
          {label: '物流单号', name: 'logisticsNumber', align: 'center'},
          {label: '操作人', name: 'operator', align: 'center'},
          {label: '接收状态', name: 'status', align: 'center', formatter: this.formatStatus},
          {label: '网点接收人', name: 'pointReceiverName', align: 'center'},
          {label: '网点接收时间', name: 'pointReceiveTime', align: 'center'},
          {label: '网点接收备注', name: 'pointReceiveRemark', align: 'center'},
          {label: '维修人', name: 'repairer', align: 'center'},
          {label: '返还人', name: 'backName', align: 'center'},
          {label: '维修工厂', name: 'factoryName', align: 'center'}
        ],
        unReturnColumn: [
          {label: '返厂批次号', name: 'batch', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', align: 'center'},
          {label: '省份', name: 'province', width: '80', align: 'center'},
          {label: '城市', name: 'city', align: 'center'},
          {label: '发送人', name: 'name', align: 'center'},
          {label: '型号', name: 'model', align: 'center'},
          {label: '维修工厂', name: 'factoryName', align: 'center'},
          {label: '维修人', name: 'repairer', align: 'center'},
          {label: '维修结果', name: 'result', align: 'center'}
        ],
        detailList: [],
        overviewList: [],
        alreadyReturnList: [],
        unReturnList: [],
        pagination: this.getData(this.getReturnList),
        pagination1: this.getData(this.onBtnReceive),
        unReturnPagination: this.getData(this.getUnreturnDeviceList),
        alreadyReturnPagination: this.getData(this.getReturnedDeviceList),
        exportLoading: false
      }
    },
    methods: {
      formatTime (row, column, cellValue) {
        return parseTime(cellValue, '{m}') + '月'
      },
      formatDate (row, column, cellValue) {
        return parseTime(cellValue, '{y}-{m}-{d}')
      },
      // 为在厂时间列添加说明
      renderHeader (h, {column, $index}) {
        return [
          column.label,
          h(
            'el-tooltip',
            {
              props: {
                content: '在厂时间 = 实时日期 - 办事处发货日期 - 7天物流时间',
                placement: 'top'
              }
            },
            [
              h('span', {
                class: {'el-icon-question': true}
              })
            ]
          )
        ]
      },
      // 格式化在厂时间(计算得到的在厂时间小于0的,看作为0)
      formatInFactoryTime (row, column, cellValue) {
        if (cellValue < 0) {
          return 0
        } else {
          return cellValue
        }
      },
      // 格式化接受日期时间戳
      formatReceiveTimestamp (row, column, cellValue) {
        if (cellValue === null) {
          return '工厂暂未接收'
        } else {
          return parseTime(cellValue, '{y}-{m}-{d} {hh}:{ii}:{ss}')
        }
      },
      // 格式化返还日期时间戳
      formatReturnTimestamp (row, column, cellValue) {
        if (cellValue === null) {
          return '工厂暂未返还'
        } else {
          return parseTime(cellValue, '{y}-{m}-{d} {hh}:{ii}:{ss}')
        }
      },
      // 设备状态格式化
      formatStatus (row, column, cellValue) {
        if (cellValue === null) {
          return '未接收'
        }
        return cellValue
      },
      formatUnRepairedNum (row, column, cellValue) {
        if (cellValue === null) {
          return 0
        }
        return cellValue
      },
      formatOweDeviceNum (row, column, cellValue) {
        if (!row.returnedNum) {
          row.returnedNum = 0
        }
        return row.returnNum - row.refusedNum - row.returnedNum
      },
      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      handleClick (activeName) {
        if (activeName === 'unReturn') {
          let listQuery = {
            pageNumber: this.unReturnPagination.currentPage,
            pageSize: this.unReturnPagination.pageSize,
            batch: this.queryBatch
          }
          this.getUnreturnDeviceList(listQuery)
        } else if (activeName === 'alreadyReturn') {
          let listQuery = {
            pageNumber: this.alreadyReturnPagination.currentPage,
            pageSize: this.alreadyReturnPagination.pageSize,
            batch: this.queryBatch
          }
          this.getReturnedDeviceList(listQuery)
        }
      },
      unOperateClick (activeName1) {
        if (activeName1 === 'unOperate') {
          let listQuery = {
            status: 0,
            pageNumber: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
          }
          this.getReturnList(listQuery)
        } else if (activeName1 === 'alreadyOperate') {
          let listQuery = {
            status: 1,
            pageNumber: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
          }
          this.getReturnList(listQuery)
        }
      },
      getReturnList (listQuery) {
        this.tableLoadingFlag = true
        if (!listQuery.batch) {
          listQuery.batch = this.listQuery.batch
        }
        if (!listQuery.factoryId) {
          listQuery.factoryId = this.listQuery.factoryId
        }
        if (!listQuery.provinceCode) {
          listQuery.provinceCode = this.listQuery.provinceCode
        }
        if (this.activeName1 === 'unOperate') {
          listQuery.status = 0
        } else if (this.activeName1 === 'alreadyOperate') {
          listQuery.status = 1
        }
        apiGetFactoryBatchInfo(listQuery).then(response => {
          this.overviewList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 页面数据导出
      factoryOverviewExport () {
        let listQuery = {
          status: '',
          userId: getUserId(),
          batch: this.searchDto.batch,
          provinceCode: this.searchDto.provinceCode,
          factoryId: this.searchDto.factoryId
        }
        if (this.activeName1 === 'unOperate') {
          listQuery.status = 0
        } else if (this.activeName1 === 'alreadyOperate') {
          listQuery.status = 1
        }
        this.exportLoading = true
        apiGetFactoryOverviewListExport(listQuery).then(response => {
          downloadExcel(response.data, '自有售后工厂批次一览信息导出表')
          this.exportLoading = false
        }).catch(() => {
          this.exportLoading = false
        })
      },
      getReturnedDeviceList (listQuery) {
        this.alreadyReturnLoadingFlag = true
        if (listQuery.batch) {
          this.batch = listQuery.batch
        } else {
          listQuery.batch = this.batch
        }
        apiGetBatchReturnedDevice(listQuery).then(response => {
          this.alreadyReturnList = response.data
          this.alreadyReturnPagination.totalRecords = response.totalRecords
          this.alreadyReturnLoadingFlag = false
        }).catch(() => {
          this.alreadyReturnLoadingFlag = false
        })
      },
      getUnreturnDeviceList (listQuery) {
        this.unReturnLoadingFlag = true
        if (listQuery.batch) {
          this.batch = listQuery.batch
        } else {
          listQuery.batch = this.batch
        }
        apiGetBatchUnreturnDevice(listQuery).then(response => {
          this.unReturnList = response.data
          this.unReturnPagination.totalRecords = response.totalRecords
          this.unReturnLoadingFlag = false
        }).catch(() => {
          this.unReturnLoadingFlag = false
        })
      },
      onBtnReceive (row) {
        this.detailDialogVisible = true
        this.detailTableLoadingFlag = true
        this.detailList = []
        if (row.batch) {
          this.batch = row.batch
        } else {
          row.batch = this.batch
        }
        let queryDto = {
          pageNumber: this.pagination1.currentPage,
          pageSize: this.pagination1.pageSize,
          batch: row.batch
        }
        apiGetBatchDeviceInfo(queryDto).then(response => {
          this.detailList = response.data
          this.pagination1.totalRecords = response.totalRecords
          this.detailTableLoadingFlag = false
        }).catch(() => {
          this.detailTableLoadingFlag = false
        })
      },
      onBtnBack (row) {
        this.queryBatch = row.batch
        this.backDialogVisible = true
        this.activeName = 'unReturn'
        this.handleClick('unReturn')
      },
      onBtnClose () {
        this.backDialogVisible = false
        this.queryBatch = ''
        this.alreadyReturnPagination.currentPage = 1
        this.alreadyReturnPagination.pageSize = 10
        this.unReturnPagination.currentPage = 1
        this.unReturnPagination.pageSize = 10
        this.alreadyReturnLoadingFlag = false
        this.unReturnLoadingFlag = false
      },
      onBtnCancel () {
        this.detailDialogVisible = false
        this.detailTableLoadingFlag = false
        this.pagination1.currentPage = 1
        this.pagination1.pageSize = 10
      },
      searchReturn () {
        this.listQuery.batch = this.searchDto.batch
        this.listQuery.factoryId = this.searchDto.factoryId
        this.listQuery.provinceCode = this.searchDto.provinceCode
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getReturnList(this.listQuery)
      },
      getFactoryList () {
        apiGetFactoryList().then(response => {
          this.factoryOption = response.data
        })
      },
      // 获取所有省份一览
      getSelectProvince () {
        apiGetCity().then(response => {
          this.allSelectProvince = response.data
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .toolbar-header {
    border-top: 1px solid #ddd;
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
    background: #eef1f6;
    height: 35px;
    .toolbar-btn {
      margin-left: 10px;
    }
  }
</style>
